package br.ufpe.cin.dsoa.qos.service.registry.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import br.ufpe.cin.dsoa.qos.service.registry.QosServiceRegistry;


@SuppressWarnings("rawtypes")
public class QosServiceRegistryImpl implements QosServiceRegistry{

	//Map<String,Map<String,ComputerStatistics>>
	private Map historical;

	public QosServiceRegistryImpl() {
		this.historical = new HashMap();
	}

	@SuppressWarnings("unchecked")
	@Override
	//<String, Map<String, Statistics>>
	public Map<String,Statistics> getHistoricalData(String pid) {
		return (Map<String,Statistics>) historical.get(pid);
	}

	@SuppressWarnings("unchecked")
	@Override
	//<String, Map<String, Statistics>>
	public Map getHistoricalData(List<String> pids) {
		Map<String, Map<String, Statistics>> returned = new HashMap();
		for(String pid : pids){
			returned.put(pid, (Map<String, Statistics>) historical.get(pid));
		}
		return returned;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void addQosData(QoSAttribute qosAttribute) {
		if(this.historical.containsKey(qosAttribute.getServiceId())){
			Map atrPerOpe = (Map) historical.get(qosAttribute.getServiceId());
			String key = returnedKey(qosAttribute);
			if(atrPerOpe.containsKey(key)){
				ComputerStatistics computerStatistics = (ComputerStatistics)atrPerOpe.get(key);
				computerStatistics.addValue(qosAttribute.getValue());	
			}
			else{
				ComputerStatistics computerStatistics = new ComputerStatistics();
				computerStatistics.addValue(qosAttribute.getValue());
				atrPerOpe.put(key, computerStatistics);
			}
		}
		else{
			newRegister(qosAttribute);
		}


	}
	
	@SuppressWarnings("unchecked")
	private void newRegister(QoSAttribute qosAttribute){
		ComputerStatistics computerStatistics = new ComputerStatistics();
		computerStatistics.addValue(qosAttribute.getValue());
		String key = returnedKey(qosAttribute);

		//Map<operation.atribute,ComputerStatistics>
		Map value = new HashMap();
		value.put(key, computerStatistics);
		this.historical.put(qosAttribute.getServiceId(), value);
		
	}
	
	private String returnedKey(QoSAttribute qosAttribute){
		String key = qosAttribute.getName() ;
		if(null != qosAttribute.getOperationName()){
			key = qosAttribute.getOperationName() + "." + qosAttribute.getName();
		}
		return key;
	}

}
